<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .progress {
        padding: 5px;
        border: 1px solid;
      }
      .progress .progressBar {
        height: 10px;
        width: 0px;
        background: gray;
      }
      .msg {
        border: solid;
        color: red;
      }
    </style>
  </head>
  <body>
    <div class="msg" id="msg"></div>
    下载进度
    <progress id="progress" value="0" max="100"></progress>

    <div class="progress">
      <div class="progressBar" id="progressBar"></div>
    </div>

    <div id="box"></div>

    <script>
      // apifox、REST Client
      // 调用后端接口（函数），需要考虑输入和输出

      function renderTable(data = []) {
        const html = String.raw;
        return html`<table border="1">
          <thead>
            <tr>
              <th>ID</th>
              <th>标题</th>
              <th>作者</th>
            </tr>
          </thead>
          <tbody>
            ${data
              .map(
                (el) => html`
                  <tr>
                    <td>${el.id}</td>
                    <td>${el.title}</td>
                    <td>${el.author}</td>
                  </tr>
                `
              )
              .join("")}
          </tbody>
        </table>`;
      }
      const xhr = new XMLHttpRequest();
      xhr.open("GET", "http://127.0.0.1:3000/posts");
      xhr.responseType = "json";
      xhr.onload = function () {
        const msg = document.getElementById("msg");
        switch (xhr.status) {
          case 400:
            msg.innerHTML = "参数错误";
            break;
          case 401:
            msg.innerHTML = "没有权限";
            break;
          case 404:
            msg.innerHTML = "资源不存在";
            break;
          default:
            document.getElementById("box").innerHTML = renderTable(
              xhr.response
            );
        }
      };
      xhr.onerror = function () {
        console.log("onerror");
      };
      xhr.onprogress = function (e) {
        let v = 0;
        if (e.total === 0) {
          v = 100;
        } else {
          v = Math.floor((e.loaded / e.total) * 100);
        }

        document.getElementById("progress").value = v;
        document.getElementById("progressBar").style.width = v + "%";
      };
      xhr.send();
    </script>
  </body>
</html>
